package com.qianfeng.openapi.search.controller;

import com.qianfeng.openapi.common.util.JSONUtil;
import com.qianfeng.openapi.search.bean.LayUITableVO;
import com.qianfeng.openapi.search.service.ElasticsearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/search/adminuser")
public class SearchAdminUserController {


    @Autowired
    private ElasticsearchService elasticsearchService;

    private final String INDEX_NAME = "openapi-adminuser";

    /**
     * 搜索功能
     * POST http://localhost:9200/search/adminuser/search
     * 请求参数
     *   JSON数据, page,size,realName,email,status
     * 响应数据
     *   LayUITableVO
     * @param parameters
     */
    @PostMapping("/search")
    public LayUITableVO search(@RequestBody Map<String,Object> parameters) throws IOException {
        //1. 调用service查询数据
        LayUITableVO vo = elasticsearchService.searchAdminUserDocument(INDEX_NAME, parameters);
        //2. 响应数据
        return vo;
    }


    /**
     * 添加功能
     * POST http://localhost:9200/search/adminuser/add
     * 请求参数: JSON -> id,realName,email,status
     * 响应: 添加失败,抛出异常
     */
    @PostMapping("/add")
    public void add(@RequestBody Map<String,Object> parameters) throws IOException {
        //1. 获取id
        String id = parameters.get("id") + "";

        //2. 封装JSON字符串
        String json = JSONUtil.toJSON(parameters);

        //3. 调用service执行添加
        elasticsearchService.addDocument(INDEX_NAME,id,json);
    }


}
